from datetime import datetime, timedelta
from flask import Blueprint, request
from models.models import GPSData, db
from utils.helpers import api_response

gps_bp = Blueprint('gps', __name__)

@gps_bp.route('', methods=['POST'])
def submit_gps_data():
    """
    提交GPS位置数据
    ---
    tags:
      - GPS数据
    parameters:
      - name: body
        in: body
        required: true
        schema:
          type: object
          required:
            - device_id
            - latitude
            - longitude
          properties:
            device_id:
              type: string
              description: 设备ID
            latitude:
              type: number
              format: float
              description: 纬度
            longitude:
              type: number
              format: float
              description: 经度
            accuracy:
              type: number
              format: float
              description: 精度(米)
    responses:
      200:
        description: GPS数据提交成功
        schema:
          type: object
          properties:
            code:
              type: integer
              example: 200
            message:
              type: string
              example: "GPS数据提交成功"
            data:
              type: object
              properties:
                data_id:
                  type: integer
                  description: 数据记录ID
      400:
        description: 参数错误
      500:
        description: 服务器内部错误
    """
    try:
        data = request.json
        required_fields = ['device_id', 'latitude', 'longitude']
        if not all(key in data for key in required_fields):
            return api_response(message="缺少必要字段: device_id, latitude, longitude", code=400, status_code=400)
            
        new_gps = GPSData(
            device_id=data['device_id'],
            latitude=data['latitude'],
            longitude=data['longitude'],
            accuracy=data.get('accuracy')
        )
        
        db.session.add(new_gps)
        db.session.commit()
        
        return api_response(
            data={"data_id": new_gps.data_id},
            message="GPS数据提交成功",
            code=200
        )
    except Exception as e:
        db.session.rollback()
        return api_response(message=str(e), code=500, status_code=500)

@gps_bp.route('/history', methods=['GET'])
def get_gps_history():
    """
    获取GPS历史数据
    ---
    tags:
      - GPS数据
    parameters:
      - name: device_id
        in: query
        type: string
        required: true
        description: 设备ID
      - name: hours
        in: query
        type: integer
        required: false
        description: 查询过去多少小时的数据
        default: 24
    responses:
      200:
        description: 查询成功
        schema:
          type: object
          properties:
            code:
              type: integer
              example: 200
            data:
              type: array
              items:
                type: object
                properties:
                  device_id:
                    type: string
                    description: 设备ID
                  latitude:
                    type: number
                    description: 纬度
                  longitude:
                    type: number
                    description: 经度
                  accuracy:
                    type: number
                    description: 精度(米)
                  time:
                    type: string
                    description: 时间戳(ISO格式)
      400:
        description: 缺少必要参数
      500:
        description: 服务器内部错误
    """
    try:
        device_id = request.args.get('device_id')
        hours = request.args.get('hours', 24, type=int)
        
        if not device_id:
            return api_response(message="需要提供device_id参数", code=400, status_code=400)
            
        time_threshold = datetime.utcnow() - timedelta(hours=hours)
        
        records = GPSData.query.filter(
            GPSData.device_id == device_id,
            GPSData.timestamp >= time_threshold
        ).order_by(GPSData.timestamp.desc()).all()
        
        return api_response(
            data=[{
                "device_id": r.device_id,
                "latitude": float(r.latitude),
                "longitude": float(r.longitude),
                "accuracy": float(r.accuracy) if r.accuracy else None,
                "time": r.timestamp.isoformat()
            } for r in records],
            code=200
        )
    except Exception as e:
        return api_response(message=str(e), code=500, status_code=500) 